package com.yx.memcache;

import java.util.concurrent.Future;

import net.spy.memcached.MemcachedClient;

public class Cached {
	private MemcachedClient memClient;

	protected Cached(MemcachedClient memClient) {
		this.memClient = memClient;
	}

	public boolean set(String key, Object value, int expire) {
		Future<Boolean> f = memClient.set(key, expire, value);
		return getBooleanValue(f);
	}

	public Object get(String key) {
		Object obj = null;
		Future<Object> f = memClient.asyncGet(key);
		try {
			obj = f.get(MemcachedManager.DEFAULT_TIMEOUT, MemcachedManager.DEFAULT_TIMEUNIT);
		} catch (Exception e) {
			f.cancel(false);
		}
		return obj;
	}

	public boolean delete(String key) {
		Future<Boolean> f = memClient.delete(key);
		return getBooleanValue(f);
	}

	private boolean getBooleanValue(Future<Boolean> f) {
		try {
			Boolean bool = f.get(MemcachedManager.DEFAULT_TIMEOUT, MemcachedManager.DEFAULT_TIMEUNIT);
			return bool.booleanValue();
		} catch (Exception e) {
			f.cancel(false);
			return false;
		}
	}

}
